using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CS490_Capstone___Stubby.Page
{
    public partial class Checkout : System.Web.UI.Page
    {
        WebServiceApplication.WebService webService = new WebServiceApplication.WebService();
        String redirectHeight = "";

        protected string PayPalTotal {get; set;}

        protected void Page_Load(object sender, EventArgs e)
        {
            DataBind();
            String browserHeight;
            int contentHeight;

            // read screen height passed through URL
            if (Request.QueryString.ToString() != "")
            {
                HtmlGenericControl searchBody = (HtmlGenericControl)Page.Master.FindControl("myBody");
                // displays the appropriate header menu
                searchBody.Attributes.Add("onload", "showJavaScriptHeader();");

                // sets browser height to the visible browser height as passed by the query string
                // sets browser height to minimum of 550px if browser height is smaller
                browserHeight = (int.Parse(Request.QueryString["height"].ToString()) > 550) 
                    ? Request.QueryString["height"].ToString() : "550";

                // adds height attribute to redirectHeight
                redirectHeight = "?height=" + Request.QueryString["height"].ToString();
            }
            else
            {
                // sets browser height to default 800px if browser height cannot be determined
                browserHeight = "800";
            }

            // calculate and set the size of the input panel to fill the screen
            content.Height = contentHeight = int.Parse(browserHeight) - 120;
            topSpacer.Height = ((contentHeight - 460) / 2) - 15 > 0 ? ((contentHeight - 460) / 2) - 15 : 0;

            // Check to make sure the user is correctly logged in. If not, redirect them to the login page.
            try
            {
                string test = Session["userName"].ToString();
                if (webService.getSession(Session["userName"].ToString()) != Session.SessionID)
                    Response.Redirect("LogIn.aspx" + redirectHeight);
            }
            catch (NullReferenceException)
            {
                // The user tried to access the page without logging in.
                // Redirect to the login page.
                Session.Remove("autoRedirect");
                Session.Add("autoRedirect", "Checkout.aspx");
                Response.Redirect("LogIn.aspx" + redirectHeight);
            }  

            Table motherTable = new Table();
            motherTable.CssClass = "motherTable";

            TableRow tablerow = new TableRow();
            TableCell tablecell = new TableCell();
            tablecell.ColumnSpan = 2;

            tablerow.Controls.Add(tablecell);
            motherTable.Controls.Add(tablerow);
            
            Table outputTable = new Table();
            outputTable.CssClass= "results";

            TableRow row1 = new TableRow();
            
            TableCell openEvent = new TableCell();
            openEvent.CssClass = "column";
            openEvent.Text = "Event";

            TableCell date = new TableCell();
            openEvent.CssClass = "column";
            openEvent.Text = "Date";
            
            TableCell venue = new TableCell();
            openEvent.CssClass = "column";
            openEvent.Text = "Venue";
            
            TableCell seat = new TableCell();
            openEvent.CssClass = "column";
            openEvent.Text = "Seat";
            
            TableCell price = new TableCell();
            openEvent.CssClass = "column";
            openEvent.Text = "Price";

            row1.Controls.Add(openEvent);
            row1.Controls.Add(date);
            row1.Controls.Add(venue);
            row1.Controls.Add(seat);
            row1.Controls.Add(price);

            outputTable.Controls.Add(row1);

            decimal priceSubTotal = 0;
            foreach (_Ticket t in (List<_Ticket>)Session["ProceedToCheckout"])
            {  
                TableRow row2 = new TableRow();

                TableCell CellOpenEvent = new TableCell();
                CellOpenEvent.CssClass = "list";
                CellOpenEvent.Text = t.eventName;

                TableCell CellDate = new TableCell();
                CellDate.CssClass = "list";
                CellDate.Text = t.dateStart.ToString();
            
                TableCell CellVenue = new TableCell();
                CellVenue.CssClass = "list";
                CellVenue.Text = t.venueName;
            
                TableCell CellRow = new TableCell();
                CellRow.CssClass = "list";
                CellRow.Text = t.row;

                TableCell CellSeat = new TableCell();
                CellSeat.CssClass = "list";
                CellSeat.Text = t.seat;
            
                TableCell CellPrice = new TableCell();
                CellPrice.CssClass = "list";
                CellPrice.Text = "$" + t.price.ToString();

                row2.Controls.Add(CellOpenEvent);
                row2.Controls.Add(CellDate);
                row2.Controls.Add(CellVenue);
                row2.Controls.Add(CellRow);
                row2.Controls.Add(CellSeat);
                row2.Controls.Add(CellPrice);

                outputTable.Controls.Add(row2);
                priceSubTotal += t.price;
            }

            TableRow row3 = new TableRow();
            
            TableCell subtotal = new TableCell();
            subtotal.CssClass = "subTotal leftNotLarge";
            subtotal.ColumnSpan = 4;
            subtotal.Text = "Subtotal:";
            tablecell.Controls.Add(outputTable);

            TableCell right = new TableCell();
            right.CssClass = "column rightNotSmall";
            right.Text = "$" + priceSubTotal.ToString();

            row3.Controls.Add(subtotal);
            row3.Controls.Add(right);

            outputTable.Controls.Add(row3);

            step1.Controls.Add(outputTable);

            step1.Controls.Add(new LiteralControl("<br /><br />"));

            Table feeSummary = new Table();
            feeSummary.CssClass = "small";

            TableRow summaryRow1 = new TableRow();
            TableCell span = new TableCell();
            span.CssClass = "column";
            span.ColumnSpan =2;
            TableCell ticketSubtotal = new TableCell();
            ticketSubtotal.CssClass = "list";
            ticketSubtotal.Text = "Ticket Subtotal";
            TableCell right2 = new TableCell();
            right2.CssClass = "list rightNotSmall";
            right2.Text = "$" + priceSubTotal.ToString();

            summaryRow1.Controls.Add(span);
            summaryRow1.Controls.Add(ticketSubtotal);
            summaryRow1.Controls.Add(right2);

            TableRow summaryRow2 = new TableRow();
            TableCell convenienceFee = new TableCell();
            convenienceFee.CssClass = "list";
            decimal convFee = (decimal)12.00;
            convenienceFee.Text = "Convenience Fee";
            TableCell right3 = new TableCell();
            right3.CssClass = "list rightNotSmall";
            right3.Text = "$" + convFee.ToString();

            summaryRow2.Controls.Add(convenienceFee);
            summaryRow2.Controls.Add(right3);
            
            TableRow summaryRow3 = new TableRow();
            TableCell availabilitySurcharge = new TableCell();
            availabilitySurcharge.CssClass = "list";
            decimal availabilityCharge = (decimal)1.00;
            availabilitySurcharge.Text = "Availability Surcharge";
            TableCell right4 = new TableCell();
            right4.CssClass = "list rightNotSmall";
            right4.Text = "$" + availabilityCharge.ToString();

            summaryRow3.Controls.Add(availabilitySurcharge);
            summaryRow3.Controls.Add(right4);

            TableRow summaryRow4 = new TableRow();
            TableCell tax = new TableCell();
            tax.CssClass = "list";
            decimal taxes = (decimal)5.00;
            tax.Text = "Tax";
            TableCell right5 = new TableCell();
            right5.CssClass = "list rightNotSmall";
            right5.Text = "$" + taxes.ToString();

            summaryRow4.Controls.Add(tax);
            summaryRow4.Controls.Add(right5);
                        
            TableRow summaryRow5 = new TableRow();
            TableCell grandTotal = new TableCell();
            grandTotal.CssClass = "subTotal leftNotLarge";
            decimal GrandTotal = priceSubTotal + convFee + availabilityCharge + taxes;
            grandTotal.Text = "Total:";
            TableCell right6 = new TableCell();
            right6.CssClass = "list rightNotSmall";
            right6.Text = "$" + GrandTotal.ToString();

            summaryRow5.Controls.Add(grandTotal);
            summaryRow5.Controls.Add(right6);

            feeSummary.Controls.Add(summaryRow1);
            feeSummary.Controls.Add(summaryRow2);
            feeSummary.Controls.Add(summaryRow3);
            feeSummary.Controls.Add(summaryRow4);
            feeSummary.Controls.Add(summaryRow5);

            step1.Controls.Add(feeSummary);
            PayPalTotal = GrandTotal.ToString();

            payPalCheckout.InnerHtml = "<a href=\'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=darthh_1336442126_biz@gmail.com&item_name=Stubby&amount=" + GrandTotal.ToString() +
                 "&undefined_quantity=0&currency_code=USD\'>" +
                 "<img src=\"https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif\"" +
                 "border=\"0\" alt=\"Buy Now Using PayPal\" /></a>";

        }

        private bool validInputStep1()
        {
            // there is no input for step 1, so return true
            return true;
        }
		
        // hides step1 to show step2
        protected void FinishStep1_Click(object sender, EventArgs e)
        {
            if (!validInputStep1())
            {
                // step 1 will validate because there is no input
            }
            else
            // beginning of the valid input block -- do what the button is supposed to do
            {
                // do what the button is supposed to do
                step1.Visible = false;
                step2.Visible = true;
            } // close of the valid input block
        }

        private bool validInputStep2()
        {
            // char arrays to test various inputs against
            char[] badChar = "*&#()[]{}%$@<>?/\\~`=!^|\":;+".ToCharArray();
            char[] badEmail = "*&#()[]{}%$<>?/\\~`=!^|\":;".ToCharArray();
            char[] badAddress = "*&()[]{}%$@<>?/\\~`=!^|\":;".ToCharArray();
            char[] badZip = "*&#()[]{}%$@<>?/\\~`=!^|\":;+".ToCharArray();
                badZip.Concat("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray());
            char[] at = "@".ToCharArray();
            char[] dot = ".".ToCharArray();

            // change background color of all fields white
            firstName.BackColor = System.Drawing.Color.White;
            lastName.BackColor = System.Drawing.Color.White;
            address1.BackColor = System.Drawing.Color.White;
            address2.BackColor = System.Drawing.Color.White;
            city.BackColor = System.Drawing.Color.White;
            state.BackColor = System.Drawing.Color.White;
            zipCode.BackColor = System.Drawing.Color.White;
            email.BackColor = System.Drawing.Color.White;
            age.BackColor = System.Drawing.Color.White;

            // highlights fields that are invalid/incomplete
            if (firstName.Text == "" || firstName.Text.IndexOfAny(badChar) >= 0)
            {
                firstName.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (lastName.Text == "" || lastName.Text.IndexOfAny(badChar) >= 0)
            {
                lastName.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (address1.Text == "" || address1.Text.IndexOfAny(badAddress) >= 0)
            {
                address1.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (city.Text == "" || city.Text.IndexOfAny(badAddress) >= 0)
            {
                city.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (state.SelectedIndex <= 0)
            {
                state.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (zipCode.Text == "" || zipCode.Text.IndexOfAny(badZip) >= 0 ||
                zipCode.Text.Length != 5)
            {
                zipCode.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (email.Text == "" || email.Text.IndexOfAny(badEmail) >= 0 ||
                email.Text.IndexOfAny(at) < 0 || email.Text.IndexOfAny(dot) < 0)
            {
                email.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            
            // checks to see if any fields are highlighted as invalid/incomplete
            if (firstName.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                lastName.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                address1.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                address2.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                city.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                state.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                zipCode.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                email.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                paymentRadios.SelectedIndex == -1 || deliveryRadios.SelectedIndex == -1)
            // invalid/incomplete input detected
            {
                return false;
            }
            else
            // no invalid/incomplete characters detected
            {
                return true;
            }
        }

        // hides step2 to show step3
        protected void finishStep2_Click(object sender, EventArgs e)
        {
            if (!validInputStep2())
            // do nothing
            {
                
            }
            else
            // beginning of the valid input block -- do what the button is supposed to do
            {
                step2.Visible = false;
                step3.Visible = true;
                if (paymentRadios.SelectedItem.Text == " PayPal")
                // displays PayPal panel if user has selected PayPal option in step 2
                {
                    payPal.Visible = true;
                }
                else if (paymentRadios.SelectedItem.Text == " Credit Card")
                // displays credit card panel if user has selected credit card option in step 2
                {
                    creditCard.Visible = true;
                }
                else
                // defaults to display PayPal panel 
                {
                    payPal.Visible = true;
                }
            } // close of the valid input block
        }

        private bool validInputStep3PayPal()
        {
            // char arrays to test various inputs against
            char[] badEmail = "*&#()[]{}%$<>?/\\~`=!^|\":;".ToCharArray();
            char[] at = "@".ToCharArray();
            char[] dot = ".".ToCharArray();

            // change background color of all fields white
            payPalUserName.BackColor = System.Drawing.Color.White;
            payPalPassword.BackColor = System.Drawing.Color.White;
            
            // payPalUserName must be an email address
            // payPalPassword must be 8 - 20 characters in length and not be the same as payPalUserName
            // authorizePayPal check box must be checked

            // highlights fields that are invalid/incomplete
            if (payPalUserName.Text == "" || payPalUserName.Text.IndexOfAny(badEmail) >= 0 ||
                payPalUserName.Text.IndexOfAny(at) < 0 || payPalUserName.Text.IndexOfAny(dot) < 0)
            {
                payPalUserName.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (payPalPassword.Text == "" || payPalPassword.Text.Length < 8 || 
                payPalPassword.Text.Length > 20 || payPalPassword.Text == payPalUserName.Text)
            {
                payPalPassword.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }

            // checks to see if any fields are highlighted as invalid/incomplete
            if (payPalUserName.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                payPalPassword.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) || 
                authorizePayPal.Checked == false)
            // invalid/incomplete input detected
            {
                return false;
            }
            // no invalid/incomplete input detected
            else
            {
                return true;
            }            
        }

        protected void payPalProceed_Click(object sender, EventArgs e)
        {
            if (!validInputStep3PayPal())
            // do nothing
            {

            }
            else
            // beginning of the valid input block -- do what the button is supposed to do
            {
                payPalProceed.Visible = false;
                payPalCheckout.Visible = true;
            } // close of the valid input block
        }
        
        private bool validInputStep3CreditCard()
        {
            // char arrays to test input against
            char[] badChar = "*&#()[]{}%$@<>?/\\~`=!^|\":;+-".ToCharArray();
                badChar.Concat("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray());
            char[] goodCreditCard = "3456".ToCharArray();

            // change background color of all fields white
            creditCardNumber.BackColor = System.Drawing.Color.White;
            creditCardSecurityCode.BackColor = System.Drawing.Color.White;
            expirationMonth.BackColor = System.Drawing.Color.White;
            expirationYear.BackColor = System.Drawing.Color.White;
            
            // strips credidCardNumber of dashes if user entered them
            creditCardNumber.Text = creditCardNumber.Text.Replace("-", "");

            // neither creditCardNumber nor creditCardSecurityCode can contain letters or special characters
            // creditCardNumber must be 16 digits long and begin with "3", "4", "5", or "6"
            // creditCardSecurityCode must be 3-4 digits
            // expirationMonth and expirationYear must be selected
            // authorizeCreditCard check box must be checked

            // highlights fields that are invalid/incomplete
            if (creditCardNumber.Text == "" || creditCardNumber.Text.IndexOfAny(badChar) >= 0 || 
                creditCardNumber.Text.Length != 16 || 
                creditCardNumber.Text[0].ToString().IndexOfAny(goodCreditCard) < 0)
            {
                creditCardNumber.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (creditCardSecurityCode.Text == "" || creditCardSecurityCode.Text.IndexOfAny(badChar) >= 0 ||
                creditCardSecurityCode.Text.Length < 3 || creditCardSecurityCode.Text.Length > 4)
            {
                creditCardSecurityCode.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (expirationMonth.SelectedIndex < 1)
            {
                expirationMonth.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }
            if (expirationYear.SelectedIndex < 1)
            {
                expirationYear.BackColor = System.Drawing.ColorTranslator.FromHtml("#FEF201");
            }

            // checks to see if any fields are highlighted as invalid/incomplete
            if (creditCardNumber.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                creditCardSecurityCode.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                expirationMonth.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                expirationYear.BackColor.Equals(System.Drawing.ColorTranslator.FromHtml("#FEF201")) ||
                authorizeCreditCard.Checked == false)
            // invalid/incomplete input detected
            {
                return false;
            }
            // no invalid/incomplete input detected
            else
            {
                return true;
            }            
        }

        protected void creditCardSubmit_Click(object sender, EventArgs e)
        {
            if (!validInputStep3CreditCard())
            // do nothing
            {

            }
            else
            // beginning of the valid input block -- do what the button is supposed to do
            {
                
            } // close of the valid input block
        }
    }
}